<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Users List</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <%= stylesheet_link_tag "../javascripts/ext/resources/css/ext-all.css" %>
        <%= stylesheet_link_tag "/stylesheets/blue.css" %>
        <%= stylesheet_link_tag "/stylesheets/images.css" %>
        <%= javascript_include_tag "/javascripts/ext/adapter/prototype/prototype.js" %>
        <%= javascript_include_tag "/javascripts/ext/adapter/prototype/scriptaculous.js" %>
        <%= javascript_include_tag "/javascripts/ext/adapter/prototype/effects.js" %>
        <%= javascript_include_tag "/javascripts/ext/adapter/prototype/ext-prototype-adapter.js" %>
        <!-- LIBS -->
        <!--<%= javascript_include_tag "/javascripts/ext/adapter/ext/ext-base.js" %>-->
        <!-- ENDLIBS -->
        <%= javascript_include_tag "/javascripts/ext/ext-all-debug.js" %>
        <%= javascript_include_tag "/javascripts/ext/build/locale/ext-lang-zh_CN.js" %>
    </head>
    <body>
        <div id="usersgrid" style="height:280px;" class="x-form-item">
            员工列表：
        </div>
        <script>
            //package("trailblazer.user");
            //package("feyaSoft.demouser");
            //Ext.namespace("trailblazer.user");
            /*
             * Ext JS Library 2.0.2
             * Copyright(c) 2006-2008, Ext JS, LLC.
             * licensing@extjs.com
             *
             * http://extjs.com/license
             */
            Ext.onReady(function(){
                Ext.QuickTips.init();
                Ext.form.Field.prototype.msgTarget = 'side';
                // fix the bug in codepress - resize
                //Ext.BoxComponent.prototype.setSize('100%', '125px');
                
                /************************************************************
                 * Display the result in page
                 * the column model has information about grid columns
                 * dataIndex maps the column to the specific data field in
                 * the data store (created below)
                 ************************************************************/
                var userCM = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), {
                    id: 'id',
                    header: "Identify",
                    dataIndex: 'id',
                    width: 150,
                    hidden: true
                }, {
                    header: "用户名",
                    width: 100,
                    dataIndex: 'username'
                }, {
                    header: "密码",
                    width: 100,
                    dataIndex: 'password'
                }, {
                    header: "登录帐号",
                    width: 100,
                    dataIndex: 'login_id'
                }, {
                    header: "工号",
                    width: 100,
                    dataIndex: 'employeeNo'
                }, {
                    header: "是否在线",
                    width: 100,
                    dataIndex: 'is_online'
                }]);
                
                /************************************************************
                 * connect to backend - grid - core part
                 * create the Data Store
                 *   connect with backend and list the result in page
                 *   through JSON format
                 ************************************************************/
                var userDS = new Ext.data.Store({
                    // load using script tags for cross domain, if the data in on the same domain as
                    // this page, an HttpProxy would be better
                    proxy: new Ext.data.HttpProxy({
                        url: '/users/getUsers'
                    }),
                    
                    // create reader that reads the Topic records
                    reader: new Ext.data.JsonReader({
                        root: 'root',
                        totalProperty: 'totalProperty',
                        id: 'id'
                    }, [{
                        name: 'id'
                    }, {
                        name: 'username'
                    }, {
                        name: 'password'
                    }, {
                        name: 'login_id'
                    }, {
                        name: 'employeeNo'
                    }, {
                        name: 'is_online'
                    }])
                });
                
                
                /************************************************************
                 * add a paging toolbar to the grid's footer
                 ************************************************************/
                var myPagingToolbar = new Ext.PagingToolbar({
                    pageSize: 10,
                    displayInfo: true,
                    displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
                    emptyMsg: "没有记录",
                    store: userDS
                });
                //data for search type
                var searchTypeArray = [['customer', '客户'], ['passenger', '常旅客'], ['linkman', '联系人']];
                var searchTypeReader = new Ext.data.ArrayReader({
                    id: 0
                }, [{
                    name: 'key'
                }, {
                    name: 'value'
                }]);
                var searchTypeStore = new Ext.data.Store({
                    reader: searchTypeReader
                });
                searchTypeStore.loadData(searchTypeArray);
                var searchTypeCombobox = new Ext.form.ComboBox({ //combobox   
                    fieldLabel: 'ComboBox',
                    resiable: true,
                    typeAhead: true,
                    handleHeight: 100, //   
                    displayField: 'value',
                    mode: 'local',
                    selectOnFocus: true,
                    triggerAction: 'all',//这个属性非常重要,可以在选择一个值以后,依然还显示其它的值.
                    //readOnly: true,
                    emptyText: '选择要搜索的类型...',
                    store: searchTypeStore //数据储存到这个comboBox   
                });
                var searchKey = new Ext.form.TextField({ //text  
                    id: 'searchkey',
                    fieldLabel: 'text',
                    name: 'text',
                    defaultType: 'textfield',
                    grow: false,
                    //allowBlank: false,
                    blankText: "这个字段最好不要为空",
                    //maskRe: /[a-zA-z]/gi
                });
                searchKey.on('specialkey', function(e){
                    // 监听回车按键
                    alert('Ok');
                    if (e.getKey() == e.ENTER && this.getValue().length > 0) {
                        alert("OK");
                        //                        ds.load({
                        //                            params: {
                        //                                start: 0,
                        //                                limit: myPageSize
                        //                            }
                        //                        });
                    }
                });
                var loginForm = new Ext.FormPanel({
                    //labelAlign: 'top',
                    labelWidth: 75, // label settings here cascade unless overridden
                    url: '/index/index',
                    frame: true,
                    //title: '系统登录',
                    bodyStyle: 'padding:5px 5px 0',
                    width: 350,
                    defaults: {
                        width: 230
                    },
                    defaultType: 'textfield',
                    
                    items: [{
                        fieldLabel: 'Name',
                        name: 'first',
                        allowBlank: false
                    }, {
                        fieldLabel: 'Password',
                        name: 'last',
                        inputType: 'password',
                        allowBlank: false
                    }]
                });
                /************************************************************
                 * Define menubar now in here
                 *   add and delete functions
                 ************************************************************/
                var menubar = [{
                    text: '增加用户',
                    tooltip: 'Add a new user',
                    iconCls: 'addItem',
                    handler: function(){
                        // add new user now - action
                        CreateUser(userDS);
                    }
                }, '-', {
                    text: '删除用户',
                    tooltip: 'Remove the selected items',
                    iconCls: 'remove',
                    handler: function(){
                        // delete user now - action
                        DeleteUser(userDS, gridPanel);
                    }
                }, '-', searchTypeCombobox, loginForm];
                /************************************************************
                 * define grid panel now
                 ************************************************************/
                var gridPanel = new Ext.grid.GridPanel({
                    border: false,
                    el: 'usersgrid',
                    ds: userDS,
                    cm: userCM,
                    //                    viewConfig: {
                    //                        forceFit: true
                    //                    },
                    loadMask: true,
                    tbar: menubar,
                    bbar: myPagingToolbar
                });
                
                //panel render
                gridPanel.render();
                // trigger the data store load
                userDS.load({
                    params: {
                        start: 0,
                        limit: 10
                    }
                });
                
                /************************************************************
                 * Action - edit
                 *   handle double click
                 *   user select one of the item and want to update it
                 ************************************************************/
                gridPanel.on('rowdblclick', function(gridPanel, rowIndex, e){
                    var selectedId = userDS.data.items[rowIndex].id;
                    EditUser(userDS, selectedId);
                });
                function onItemCheck(item, checked){
                    Ext.example.msg('Item Check', 'You {1} the "{0}" menu item.', item.text, checked ? 'checked' : 'unchecked');
                }
            });
            //---------------------Create User------------------------
            function CreateUser(dataStore){
            
                // pre-define fields in the form
                var username = new Ext.form.TextField({
                    fieldLabel: '姓名',
                    allowBlank: false,
                    name: 'username',
                    anchor: '90%'
                });
                
                var password = new Ext.form.TextField({
                    fieldLabel: '密码',
                    allowBlank: false,
                    name: 'password',
                    anchor: '90%'
                });
                
                var employeeNo = new Ext.form.TextField({
                    fieldLabel: '员工ID',
                    allowBlank: false,
                    name: 'employeeNo',
                    anchor: '90%'
                });
                
                var loginid = new Ext.form.TextField({
                    fieldLabel: '登录ID',
                    allowBlank: false,
                    name: 'login_id',
                    anchor: '90%'
                });
                
                var formPanel = new Ext.form.FormPanel({
                
                    baseCls: 'x-plain',
                    labelWidth: 75,
                    url: '/users/addUser',
                    defaultType: 'textfield',
                    
                    items: [username, password, employeeNo, loginid]
                });
                
                // define window and show it in desktop
                var window = new Ext.Window({
                    title: '增加新员工',
                    width: 300,
                    height: 200,
                    minWidth: 300,
                    minHeight: 250,
                    layout: 'fit',
                    plain: true,
                    bodyStyle: 'padding:5px;',
                    buttonAlign: 'center',
                    items: formPanel,
                    
                    buttons: [{
                        text: '增加',
                        handler: function(){
                            // check form value 
                            if (formPanel.form.isValid()) {
                                formPanel.form.submit({
                                    waitMsg: 'In processing',
                                    success: function(form, action){
                                        Ext.MessageBox.alert('Confirm', '提交成功');
                                        window.hide();
                                        dataStore.load({
                                            params: {
                                                start: 0,
                                                limit: 10
                                            }
                                        });
                                    },
                                    failure: function(form, action){
                                        Ext.MessageBox.alert('提交错误消息', '提交失败');
                                    },
                                });
                            }
                            else {
                                Ext.MessageBox.alert('错误提示', '请按要求填写必输选项.');
                            }
                        }
                    }, {
                        text: '取消',
                        handler: function(){
                            window.hide();
                        }
                    }]
                });
                
                window.show();
            };
            //----------------Delete User--------------------------
            function DeleteUser(dataStore, gridPanel){
            
                // get the selected items
                var m = gridPanel.getSelections();
                if (m.length > 0) {
                    Ext.MessageBox.confirm('提示', '你真的要删除这些用户吗？', function(btn){
                        if (btn == 'yes') {
                            var jsonData = "[";
                            for (var i = 0, len = m.length; i < len; i++) {
                                var ss = "{\"id\":\"" + m[i].get("id") + "\"}";
                                if (i == 0) 
                                    jsonData = jsonData + ss;
                                else 
                                    jsonData = jsonData + "," + ss;
                                dataStore.remove(m[i]);
                            }
                            jsonData = jsonData + "]";
                            //Ext.MessageBox.alert(jsonData);
                            dataStore.load({
                                params: {
                                    start: 0,
                                    limit: 10,
                                    delData: jsonData
                                }
                            });
                        }
                    });
                }
                else {
                    Ext.MessageBox.alert('错误提示', '要删除用户时，请至少选择一个用户');
                }
            };
            
            //------------Edit User-----------------
            function EditUser(dataStore, selectedId){
            
                // pre-define fields in the form
                var username = new Ext.form.TextField({
                    fieldLabel: '姓名',
                    allowBlank: false,
                    name: 'username',
                    anchor: '90%'
                });
                
                var password = new Ext.form.TextField({
                    fieldLabel: '密码',
                    allowBlank: false,
                    name: 'password',
                    anchor: '90%'
                });
                
                var employeeNo = new Ext.form.TextField({
                    fieldLabel: '员工ID',
                    allowBlank: false,
                    name: 'employeeNo',
                    anchor: '90%'
                });
                
                var loginid = new Ext.form.TextField({
                    fieldLabel: '登录ID',
                    allowBlank: false,
                    name: 'login_id',
                    anchor: '90%'
                });
                
                // create form panel
                var editFormPanel = new Ext.form.FormPanel({
                    baseCls: 'x-plain',
                    labelWidth: 75,
                    url: '/users/editUser?id=' + selectedId,
                    reader: new Ext.data.JsonReader({
                        root: 'root'
                    }, ['id', 'username', 'password', 'employeeNo', 'loginid']),
                    
                    items: [username, password, employeeNo, loginid]
                });
                
                // load form and assign value to fields
                editFormPanel.form.load({
                    url: '/users/getUserByID?id=' + selectedId,
                    waitMsg: '正在载入数据...',
                    success: function(form, action){
                        //Ext.MessageBox.alert('提示信息', '信息加载成功！');
                    },
                    failure: function(form, action){
                        Ext.MessageBox.alert('提示信息', '信息加载失败');
                    }
                });
                
                // define window and show it in desktop
                var editWindow = new Ext.Window({
                    title: '编辑用户',
                    width: 300,
                    height: 200,
                    minWidth: 300,
                    minHeight: 250,
                    layout: 'fit',
                    plain: true,
                    bodyStyle: 'padding:5px;',
                    buttonAlign: 'center',
                    items: editFormPanel,
                    
                    buttons: [{
                        text: '提交',
                        handler: function(){
                            // check form value 
                            if (editFormPanel.form.isValid()) {
                                editFormPanel.form.submit({
                                    params: {
                                        id: selectedId
                                    },
                                    waitMsg: '处理过程中...',
                                    failure: function(form, action){
                                        //debugger;
                                        Ext.MessageBox.alert('错误提示', action.failureType);//.errorInfo +'提交不成功');
                                        //Ext.MessageBox.alert('错误提示', action.result.errors.msg);
                                        //Ext.MessageBox.alert('错误提示', action.result.errors);
                                        //alert(action.result.errors.msg);
                                        //var errors = action.result.errors;
                                        //Ext.Msg.alert('服务器端异常信息', 'id:' + action.result.errors.id + ' - msg:' + action.result.errors.msg);
                                        //Ext.MessageBox.alert('错误提示', action.result.errors);
                                    },
                                    success: function(form, action){
                                        Ext.MessageBox.alert('确认', '提交成功');
                                        editWindow.hide();
                                        dataStore.load({
                                            params: {
                                                start: 0,
                                                limit: 10
                                            }
                                        });
                                    }
                                });
                            }
                            else {
                                Ext.MessageBox.alert('错误提示', '请按要求填写必输选项.');
                            }
                        }
                    }, {
                        text: '取消',
                        handler: function(){
                            editWindow.hide();
                        }
                    }]
                });
                editWindow.show();
            };
        </script>
    </body>
</html>
